//////////////////////////////////////////////////////////////////////////

#ifndef _DEVICEINTERFACE_H_
#include "deviceinterface.h"
#endif

#ifndef _RESEARCH_H_
#include "research.h"
#endif

#include <fstream>
#include <algorithm>

//////////////////////////////////////////////////////////////////////////


DeviceInterface::DeviceInterface()
{
    m_Data.reserve(60000);
}


//////////////////////////////////////////////////////////////////////////


void DeviceInterface::ReadData( Research& _research ) const
{
    if (m_Data.empty())
        throw "Research data error";

    size_t count = 1;
    for (size_t i = 1; i < m_Data.size(); i++)
    {
        if ( m_Data[i-1] == m_Data[i] )
            ++count;
        else
        {
            _research.AddData(m_Data[i-1], count);
            count = 1;
        }
    }

    _research.AddData(m_Data.back(), count);
}


//////////////////////////////////////////////////////////////////////////


void DeviceInterface::Start()
{
    if ((m_Comport = fopen("COM1", "r+")) == NULL)
    {
        if ((m_Comport = fopen("COM2", "r+")) == NULL)
            throw "Cannot open COM port";
    }

    // Start read to the memory
    fputc( 'b', m_Comport);
    fflush(m_Comport);

    // Start timer
    m_Timer.Start();
}


//////////////////////////////////////////////////////////////////////////


void DeviceInterface::Stop()
{
    //#define _DUMP_ //Uncomment it to dump read data to file

    // Stop timer
    size_t milliseconds = m_Timer.Milliseconds();

    if (milliseconds > 64)
        milliseconds -= 64;

    if ( !m_Comport )
        throw;

    // Start read from the com port
    fputc( 'c', m_Comport);
    fflush(m_Comport);

    // Skip unused data
    int cnt = 34;    
    while ( --cnt ) 
    {
        fgetc(m_Comport);
    }

    m_Data.resize(milliseconds);

    // Read data
    fread( &m_Data[0], sizeof(char), milliseconds, m_Comport );

#ifdef _DUMP_
    std::ofstream f("out.txt");
    std::ofstream f2("out2.txt");

    // Valid data
    std::copy( m_Data.begin(), m_Data.end(), std::ostream_iterator<char>(f) );

    // Invalid data
    char c;
    while ( (c = fgetc(m_Comport) ) != EOF )
        f2 << c;

    f.close();
    f2.close();
#endif

    fclose(m_Comport);
}


//////////////////////////////////////////////////////////////////////////
